#include "socket.h"
#include "logger.h"
#include <strings.h>
#include <sys/socket.h>
#include <unistd.h>
#include <netinet/tcp.h> 

Socket::~Socket(){
    close(sockfd_);
}

void Socket::bindAddress(const InetAddress& localAddr){
    const sockaddr_in* addr = localAddr.getSockAddr();
    
    if(0 != ::bind(sockfd_, (sockaddr*)addr, sizeof(sockaddr_in))){
        LOG_FATAL("bind sockfd:%d fail \n", sockfd_);
    }

}
void Socket::listen(){
    if(0 != ::listen(sockfd_, 1024)){
        LOG_FATAL("listen sockfd:%d fail \n", sockfd_);
    }
}

int Socket::accept(InetAddress* peerAddr){
    sockaddr_in client_addr;
    socklen_t len = sizeof(sockaddr_in);
    bzero(&client_addr, len);

    int connfd = ::accept(sockfd_, (sockaddr*)&client_addr, &len);
    if(connfd >= 0){
        peerAddr->setSockAddr(client_addr);
    }
    return connfd;
}

void Socket::shutdownWrite(){
    if(::shutdown(sockfd_, SHUT_WR) < 0){
        LOG_ERROR("shutdownWrite sockfd:%d error \n", sockfd_);
    }
}
void Socket::setTcpNoDelay(bool on){
    int optval = on ? 1 : 0;
    ::setsockopt(sockfd_, IPPROTO_TCP, TCP_NODELAY, &optval, sizeof(optval));
}
void Socket::setReuseAddr(bool on){
    int optval = on ? 1 : 0;
    ::setsockopt(sockfd_, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval));
}
void Socket::setReusePort(bool on){
    int optval = on ? 1 : 0;
    ::setsockopt(sockfd_, SOL_SOCKET, SO_REUSEPORT, &optval, sizeof(optval));
}
void Socket::setKeepAlive(bool on){
    int optval = on ? 1 : 0;
    ::setsockopt(sockfd_, SOL_SOCKET, SO_KEEPALIVE, &optval, sizeof(optval));
}
